#include "database.h"

Database::Database() {}

Database::Database(QString databaseName)
{
    this->myDB = QSqlDatabase::addDatabase("QSQLITE");
    this->myDB.setDatabaseName(databaseName);
}

Database::~Database()
{
    Database::myClose();
    qDebug() << "数据库已关闭";
}

bool Database::myOpen()
{
    if(!myDB.open())
    {
        qDebug() << "打开数据库失败:" << myDB.lastError().text();
        return 0;
    }
    else
    {
        qDebug() << "打开" << myDB.databaseName() << "数据库成功";
        return 1;
    }
}

void Database::myClose()
{
    this->myDB.close();
    qDebug() << "数据库底层关闭接口调用";
}

QSqlQuery Database::executeQuery(QString query,const QList<QVariant>& params)
{
    QSqlQuery tmpQ(this->myDB);
    tmpQ.prepare(query);

    for(int i = 0; i < params.size(); ++i)
    {
        tmpQ.addBindValue(params[i]);
    }

    if(!tmpQ.exec())
    {
        qDebug() << "查询失败:" << tmpQ.lastError().text();
    }

    return tmpQ;
}

